import baseUrl from "./baseUrl";

export default class request {
  // 封装请求方法
  request(options) {
    uni.showLoading({
      title: "加载中",
    });
    const { url, data, method, header } = options;
    try {
      return new Promise((resolve, reject) => {
        uni.request({
          url: baseUrl + url,
          method: method,
          data: data,
          header: header || {},
          success: (res) => {
            uni.hideLoading();
            resolve(res.data);
          },
          fail: (err) => {
            uni.hideLoading();
            reject(err);
          },
        });
      });
    } catch (error) {
      uni.hideLoading();
      reject(error);
    }
  }

  // 封装GET请求方法
  get(url, data, header) {
    return this.request({ url, data, method: "GET", header });
  }

  // 封装POST请求方法
  post(url, data, header) {
    return this.request({ url, data, method: "POST", header });
  }

  // 封装DELETE请求方法
  delete(url, data) {
    return this.request({ url, data, method: "DELETE" });
  }
  // 上传文件
  upload(url, filePath, name = "file", formData = {}) {
    return this.uploadFile({ url, filePath, name, formData });
  }
  // 封装上传文件方法
  uploadFile(options) {
    uni.showLoading({
      title: "上传中...",
    });
    const { url, filePath, name, formData } = options;
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: baseUrl + url,
        filePath: filePath,
        name: name,
        formData: formData,
        success: (res) => {
          let data = JSON.parse(res.data);
          resolve(data);
          uni.hideLoading();
        },
        fail: (err) => {
          // reject(err);
          console.log(err);
          uni.hideLoading();
        },
      });
    });
  }
}
